#!/usr/bin/env python3
"""
结果分析脚本
用于分析CSV模拟测试的结果文件，统计睡眠阶段分布和时间范围
"""

import json
from datetime import datetime
import sys

def analyze_results(filename):
    """分析测试结果文件"""
    try:
        with open(filename, 'r', encoding='utf-8') as f:
            data = json.load(f)
        
        print(f"总结果数量: {len(data)}")
        
        # 统计成功和失败的分析
        successful_analyses = []
        error_analyses = []
        
        for result in data:
            if 'error' in result and result['error']:
                error_analyses.append(result)
            elif 'response' in result and result['response']:
                successful_analyses.append(result)
            else:
                # 处理可能的其他格式
                if 'timestamp_readable' in result:
                    successful_analyses.append(result)
                else:
                    error_analyses.append(result)
        
        print(f"成功分析: {len(successful_analyses)}")
        print(f"分析错误: {len(error_analyses)}")
        
        if successful_analyses:
            # 获取时间范围
            timestamps = []
            for result in successful_analyses:
                if 'timestamp_readable' in result:
                    timestamps.append(result['timestamp_readable'])
            
            if timestamps:
                print(f"时间范围: {min(timestamps)} 到 {max(timestamps)}")
            
            # 统计睡眠阶段分布
            stages = {}
            for result in successful_analyses:
                if 'response' in result and result['response'] and 'sleep_stage' in result['response']:
                    stage = result['response']['sleep_stage']
                    stages[stage] = stages.get(stage, 0) + 1
            
            print("睡眠阶段分布:")
            for stage, count in stages.items():
                print(f"  {stage}: {count}")
            
            # 显示前5个结果的详细信息
            print("\n前5个结果详情:")
            for i, result in enumerate(successful_analyses[:5]):
                if 'timestamp_readable' in result and 'response' in result:
                    response = result['response']
                    print(f"{i+1}. 时间: {result['timestamp_readable']}, "
                          f"睡眠阶段: {response.get('sleep_stage', 'N/A')}, "
                          f"置信度: {response.get('confidence', 'N/A'):.3f}")
        
        if error_analyses:
            print(f"\n错误分析数量: {len(error_analyses)}")
            if error_analyses[0].get('error'):
                print(f"第一个错误信息: {error_analyses[0]['error']}")
        
    except FileNotFoundError:
        print(f"文件 {filename} 不存在")
    except json.JSONDecodeError:
        print(f"文件 {filename} 不是有效的JSON格式")
    except Exception as e:
        print(f"分析文件时出错: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    filename = "csv_simulation_results_1760174574.json"
    analyze_results(filename)